

const crypto = require('crypto');
const NodeRSA = require("node-rsa");


function insertStr(str, insertStr, sn) {
    var newstr = '';
    for (var i = 0; i < str.length; i += sn) {
    var tmp = str.substring(i, i + sn);
    newstr += tmp + insertStr;
    }
return newstr;
}

const getPrivateKey = function(key) {
    const result = insertStr(key, '\n', 64);
    return '-----BEGIN PRIVATE KEY-----\n' + result + '-----END PRIVATE KEY-----';
};

const getPublicKey = function(key) {
    const result = insertStr(key, '\n', 64);
    return '-----BEGIN PUBLIC KEY-----\n' + result + '-----END PUBLIC KEY-----';
};


/**
 * 生成 sha1WithRSA 签名
 * @param string toSign 数据
 * @param string privateKey 私钥
 * @return string
 */
module.exports.getSign = function(toSign, privateKey){
	let key = new NodeRSA({b: 1024 });
    key.importKey(privateKey, 'pkcs8'); //根据java端模式
    key.setOptions({ signingScheme: 'sha1' });//指定加密格式
    return  key.sign(toSign, 'base64', 'utf8');;
}


module.exports.verify = function(textdata,toSign, publicKey){
	let verify = crypto.createVerify('RSA-SHA1');
    verify.update(textdata);
    verify.end();
    return verify.verify(getPublicKey(publicKey), Buffer.from(toSign, 'base64'));
}

